#include <stdio.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_uart.h"
#include "iot_errno.h"

#define TASK_STACK_SIZE         1024*4                //任务栈大小
#define TASK_PRIO               20                    //任务优先级
#define IOT_UART_IDX            1                     //UART端口索引
#define BUFF_SIZE               100                   //缓冲区大小

static const unsigned char *data = "message from esp32"; //发送的数据
static volatile bool dataEdgeDetected = false; // 数据跳变标志位

void UartInterruptHandler(void) {
    // 检查是否有数据接收
    if (IotUartIsDataReceived(IOT_UART_IDX)) {
        // 读取数据并清空缓冲区
        uint8_t temp;
        IotUartRead(IOT_UART_IDX, &temp, 1);
        
        // 标记数据跳变
        dataEdgeDetected = true;
    }
}

void IotUartTask(void) {
    int32_t ret;

    uint8_t uart_buff[BUFF_SIZE] = {0};
    uint8_t *uart_buff_p = uart_buff;
    
    IotUartAttribute uart_attr = {
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };

    // 初始化UART驱动
    ret = IoTUartInit(IOT_UART_IDX, &uart_attr);
    if (ret != IOT_SUCCESS) {
        printf("Init Uart Failed Error No : %d\n", ret);
        return;
    }

    // 注册UART中断服务程序
    IoTUartRegisterInterruptCallback(IOT_UART_IDX, UartInterruptHandler);

    printf("Uart Test Start!!!\n");
    ret = IoTUartWrite(IOT_UART_IDX, (unsigned char*)data, strlen((const char *)data));
    if (ret != IOT_SUCCESS) {
        printf("Uart Write Failed Error No : %d\n", ret);
        IoTUartDeinit(IOT_UART_IDX);
        return;
    }

    while (1) {
        if (dataEdgeDetected) {
            // 读取数据
            ret = IoTUartRead(IOT_UART_IDX, uart_buff_p, BUFF_SIZE);
            if (ret > 0) {
                uart_buff_p[ret] = '\0';
                printf("read : %s\r\n", uart_buff_p);
                // 上报数据
                // ReportData(uart_buff_p);
            }
            dataEdgeDetected = false; // 重置标志位
        }
        memset(uart_buff_p, 0, BUFF_SIZE);
        osDelay(1000);
    }

    IoTUartDeinit(IOT_UART_IDX);
    printf("uart deinit success\r\n");
    osThreadExit();
}

void IotUartDemo(void) {
    osThreadAttr_t attr;

    attr.name = "Iot_UART_TASK_NAME";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)IotUartTask, NULL, &attr) == NULL) {
        printf("Failed to create thread!\n");
    }
}

APP_FEATURE_INIT(IotUartDemo);